<template>
	<view class="recharge" :style="css.page+'min-height:'+$xyfun.xysys().windowHeight+'px'" v-if="!empty">
		<view class="top ovh tc" :style="css.mcbg">
			<image :src="store.images[0]" />
		</view>

		<view class="store m-30 p-lr-30 p-tb-40 br-10 bc-w">
			<xy-store-row :item="store" text="当前场馆" />
		</view>

		<view class="recharge-box m-30 p-tb-40 p-lr-30 br-10 bc-w" v-if="rechargeList && rechargeList.length">
			<view class="title tb ts-32 lh-32 flex">
				<view class="line m-r-10" :style="css.mcbg"></view>充值套餐
			</view>

			<view class="recharge-list flex">
				<view class="item br-10 tc m-t-30 p-tb-40 bl" v-for="(item,index) in rechargeList" :key="item.id"
					:style="(item.id == recharge_id)?css.blc+css.pbg:css.bl"
					@tap="changeRecharge(item.id,index,item.facevalue)">
					<view class="ts-38 tb" :style="css.tcp">{{item.facevalue}}元</view>
					<view class="m-t-15 ts-26">售价{{item.buyprice}}元</view>
				</view>
			</view>

			<view class="title tb ts-32 lh-32 flex m-t-50">
				<view class="line m-r-10" :style="css.mcbg"></view>套餐说明
			</view>

			<view class="m-t-30">
				<view class="ts-28" v-for="(item,index) in rechargeList" :key="index">
					<view v-if="item.id == recharge_id">{{item.remark}}</view>
				</view>
			</view>
		</view>

		<!-- 如果没有充值套餐，则显示提示信息 -->
		<view v-else class="no-recharge-package">
			<text class="ts-28">该店铺暂未设置充值套餐</text>
		</view>

		<view class="bottom-fixed flex tc bc-w" v-if="recharge_id > 0">
			<view class="p-lr-30 p-tb-20 flex tc wa">
				<view class="l flex p-t-20 lh-40">
					<view :style="css.tcp" class="ts-40 tb"><text
							class="ts-26">¥</text>{{rechargeList[rechargeIndex].buyprice}}</view>
				</view>
				<view class="action flex m-l-auto">
					<view class="buy m-l-auto tc-w" :style="css.mcbg" @tap="createOrder">
						确认充值
					</view>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import Pay from '@/utils/pay';
	import xyStoreRow from '@/components/xy-store/row';
	export default {
		components: {
			xyStoreRow,
		},
		data() {
			return {
				css: {},
				lat: 0,
				lng: 0,
				empty: true,
				store_id: 0,
				store: {},
				rechargeList: [],
				recharge_id: 0,
				rechargeIndex: 0,
				disabled: false,
				money: 0,
				ismoney: false, //其他金额
				payList: [{
					name: '微信支付',
					method: 'wechat',
					icon: 'wechat',
					state: true,
					select: true
				}]
			}
		},
		computed: {
			...mapState(['common', 'user'])
		},
		async onLoad() {
			this.$xyfun.setNavBg();
			this.css = this.$xyfun.css();
			this.$xyfun.loc().then((res) => {
				this.lat = res.latitude;
				this.lng = res.longitude;
				this.loadData();
			}, () => {
				this.loadData();
			})
		},
		methods: {

			async loadData() {
				this.recharge_id = 0;

				this.$xyfun.storeId().then((store_id) => {
					this.store_id = store_id;
					this.$api.get({
						url: '/store/detail',
						loadingTip: '加载中...',
						data: {
							id: store_id,
						},
						success: res => {
							this.store = res;
							this.store.distance = this.$xyfun.algorithm([res.latitude, res
								.longitude
							], [this.lat, this.lng]);
						}
					});
				})

				this.$xyfun.storeId().then((store_id) => {
					this.$api.get({
						url: '/common/recharge',
						loadingTip: '加载中...',
						data: {
							store_id: store_id,
						},
						success: res => {
							this.empty = false;

							console.log('res', res);
							this.rechargeList = res;

							if (res && res.length > 0) {
								if (this.$Route.query.recharge_id != undefined) {
									this.recharge_id = this.$Route.query.recharge_id;
								}

								if (this.recharge_id > 0) {
									res.forEach((item, index) => {
										if (item.id == this.recharge_id) {
											this.rechargeIndex = index;
										}
									})
								} else {
									this.recharge_id = res && res.length ? res[0].id : 0;
								}

							}
						}
					});
				});
			},

			//Recharge切换
			changeRecharge(recharge_id, index, facevalue) {
				this.recharge_id = recharge_id;
				this.rechargeIndex = index;
				this.money = facevalue
			},

			//场馆切换
			changeStore(store_id) {
				if (this.store_id != store_id) {
					this.store_id = store_id;
					this.recharge_id = 0;
					this.loadData();
				}
			},

			//创建订单
			createOrder() {
				if (this.disabled) {
					return;
				}
				this.disabled = true;

				var pay_type = '';
				this.payList.map((value) => {
					if (value.select) {
						pay_type = value.method;
					}
				});
				if (!pay_type) {
					this.$xyfun.msg('请选择支付方式');
					this.disabled = false;
				} else {
					// 提交订单
					this.$xyfun.storeId().then((store_id) => {
						this.$api.post({
							url: '/recharge_order/add',
							data: {
								store_id: store_id,
								recharge_id: this.recharge_id,
								pay_type: "wechat",
								ismoney: false,
								money: this.money
							},
							loadingTip: '提交订单中...',
							success: res => {
								console.log(res)
								//发起支付
								this.$api.post({
									url: '/Shande/recharge',
									data: {
										orderjson: res
									},
									success: res => {
										const jsonData = JSON.parse(res.data);
										const payDataString = jsonData
											.pay_data; // 获取 pay_data 的 JSON 字符串
										const payData = JSON.parse(payDataString); // 解析成对象
										uni.requestPayment({
											appId: payData.appId,
											nonceStr: payData.nonceStr,
											package: payData.package,
											paySign: payData.paySign,
											signType: payData.signType,
											timeStamp: payData.timeStamp,
											success: (e) => {
											    uni.showModal({
											        content: "充值成功",
											        showCancel: false,
											        success: (res) => {
														console.log("res.confirm:" + res.confirm);
											            if (res.confirm) {
															uni.switchTab({
																url: '/pages/user'  // 这里使用 switchTab 进行跳转
															});
											            }
											        }
											    });
											},
											fail: (e) => {
												uni.showModal({
													content: "支付取消",
													showCancel: false
												})
											}
										})
									},
									fail: res => {
										console.log(res);
										this.disabled = false;
									}
								});
							},
							fail: res => {
								console.log(res);
								this.disabled = false;
							}
						});
					})
				}
			},
			
			
			// addBalance() {
			// 	// 直接从本地存储中获取 userId 和 storeId
			// 	uni.getStorage({
			// 		key: 'xyvenue:user',
			// 		success: (res) => {
			// 			const userId = res.data.id; // 假设用户ID存储在 res.data.id 中
			// 			const storeId = res.data.store_id; // 假设门店ID存储在 res.data.store_id 中
			// 			const amount = this.money; // 充值金额

			// 			// 发起充值请求
			// 			this.$api.post({
			// 				url: '/user_balance/recharge',
			// 				data: {
			// 					user_id: userId,
			// 					store_id: storeId,
			// 					amount: amount
			// 				},
			// 				loadingTip: '充值余额中...',
			// 				success: res => {
			// 					// 充值成功后的处理
			// 					console.log('余额充值成功:', res);
			// 					this.$xyfun.msg('充值成功');
			// 					// 弹窗提示充值成功
			// 					uni.showModal({
			// 						title: '充值成功',
			// 						content: '充值成功，详情可去我的钱包页面查看',
			// 						showCancel: false, // 不显示取消按钮
			// 						confirmText: '查看钱包', // 确认按钮文字
			// 						success: (modalRes) => {
			// 							if (modalRes.confirm) {
			// 								// 用户点击了 "查看钱包" 按钮，跳转到钱包页面
			// 								uni.navigateTo({
			// 									url: '/pages/user/balance/detail' // 根据实际钱包页面的路径修改
			// 								});
			// 							}
			// 						}
			// 					});
			// 				},
			// 				fail: res => {
			// 					// 充值失败后的处理
			// 					console.log('余额充值失败:', res);
			// 					this.$xyfun.msg('充值失败，请稍后重试');
			// 				}
			// 			});
			// 		},
			// 		fail: () => {
			// 			this.$xyfun.msg('获取用户信息失败，请重新登录');
			// 		}
			// 	});
			// },

			//支付方式选择
			payMethodSelect(key) {
				this.payList.map((value, index) => {
					if (index == key) {
						value.select = !value.select;
					} else {
						value.select = false;
					}
				});
			},

		}
	}
</script>

<style scoped lang="scss">
	.recharge {
		padding-top: 290rpx;

		.top {
			position: absolute;
			width: 100%;
			height: 400rpx;
			top: 0;
			left: 0;
			z-index: 1;

			image {
				width: 750rpx;
				height: 400rpx;
			}
		}

		.store {
			z-index: 100;
			position: relative;
		}

		.line {
			width: 6rpx;
			border-radius: 5rpx;
			height: 30rpx;
		}

		.recharge-box {

			.recharge-list {
				.item {
					width: 296rpx;
					margin-right: 30rpx;
					border-size: 4rpx;

					.buy {
						width: 146rpx;
						height: 56rpx;
						line-height: 56rpx;
						border-radius: 28rpx;
						margin: 0 auto;
					}
				}

				.item:nth-child(2n) {
					margin-right: 0;
				}
			}
		}

		.bottom-fixed {
			.buy {
				width: 240rpx;
				height: 80rpx;
				border-radius: 40rpx;
				line-height: 80rpx;
			}
		}

		.buy-model-box {
			width: 100%;
			border-radius: 20rpx 20rpx 0 0;

			.confirm {
				width: 240rpx;
				height: 80rpx;
				border-radius: 40rpx;
				line-height: 80rpx;
			}
		}

		.no-recharge-package {
			margin-top: 50rpx;
			text-align: center;
			font-size: 32rpx;
			color: #ff5a5f;
			font-weight: bold;
			line-height: 100rpx;
			background-color: rgba(255, 90, 95, 0.1);
			border-radius: 12rpx;
			padding: 20rpx;
			box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
			max-width: 650rpx;
			margin-left: auto;
			margin-right: auto;
		}
	}
</style>